<?php
namespace Foam\Model;

use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Where;

class FamilleTable extends AbstractTableGateway
{
    protected $table ='foam_famille';
    
    public function __construct(Adapter $adapter)
    {
        $this->adapter = $adapter;
        $this->resultSetPrototype = new ResultSet();
        $this->resultSetPrototype->setArrayObjectPrototype(new Famille());
        $this->initialize();
    }
    
    public function fetchAll()
    {
        $adapter = $this->adapter;
        $sql = new Sql($adapter);
        $select = $sql->select();
        $select->from($this->table);
        $select->order('libelle ASC');
        
        $selectString = $sql->getSqlStringForSqlObject($select);
        $results = $adapter->query($selectString, $adapter::QUERY_MODE_EXECUTE);   
        return $results;
    }
    
    public function getFamille($id)
    {
        $id  = (int) $id;
        $rowset = $this->select(array('id_famille' => $id));
        $row = $rowset->current();
        if (!$row) {
            throw new \Exception("Could not find row $id");
        }
        return $row;
    }
    
    public function getList()
    {
        $sql = new Sql($this->adapter);
        $select = $sql->select();
        $select->columns(array(
            'value' => 'id_famille', 
            'text' => 'libelle'
        ));
        $select->from($this->table);
        $select->order('libelle ASC');
        
        $statement = $sql->prepareStatementForSqlObject($select);
        $result = $statement->execute();
        return $result;
    }
    
    public function saveNew($id_famille,$libelle,$description,$couleur_fond,$couleur_bordure)
    {        
        $data = array(
            'id_famille' => $id_famille,
            'libelle' => $libelle,
            'description' => $description,
            'couleur_fond' => $couleur_fond,
            'couleur_bordure' => $couleur_bordure,
        );
        
        $this->insert($data);
    }
    
    public function xeditUpdate($pk, $name, $value)
    {
        $data = array(
            $name => $value,
        );
        
        $this->update($data, array('id_famille' => $pk));
    }
    
    public function deleteFamille($id)
    {
        $this->delete(array('id_famille' => $id));
    }
}
